package com.tico.translatereditor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tico.common.service.impl.AbstractService;
import com.tico.common.utils.BaseQuery;
import com.tico.common.utils.QueryResult;
import com.tico.translatereditor.domain.Kafka;
import com.tico.translatereditor.domain.KeyValuePair;
import com.tico.translatereditor.domain.MessageModel;
import com.tico.translatereditor.domain.TranslaterData;
import com.tico.translatereditor.kafkaThread.ProducerKafka;
import com.tico.translatereditor.mapper.KeyValuePairMapper;
import com.tico.translatereditor.service.KafkaService;
import com.tico.translatereditor.service.KeyValuePairService;
import com.tico.translatereditor.service.TranslaterDataService;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 */
@Service
public class KeyValuePairServiceImpl extends AbstractService<KeyValuePair> implements KeyValuePairService {


   @Autowired
   KeyValuePairMapper keyValuePairMapper;
   @Autowired
   KafkaService kafkaService;
   @Autowired
   TranslaterDataService translaterDataService;

   @Override
   public KeyValuePair findById(Serializable id) {
     return keyValuePairMapper.findById(id);
   }

    @Override
    public List<KeyValuePair> findByIds(List<String> ids) {
        return keyValuePairMapper.findByIds(ids);
    }

    @Override
    public int insertBatch(List<KeyValuePair> keyValuePairs) {
      return keyValuePairMapper.insertBatch(keyValuePairs);
    }

    @Override
    public int insert(KeyValuePair keyValuePair) {
      return keyValuePairMapper.insert(keyValuePair);
    }
    @Override
    public List<KeyValuePair > findByNamedParamList(Map<String,Object> param){
        return keyValuePairMapper.findByNamedParamList(param);
    }

    @Override
    public int delete(Serializable id) {
      return keyValuePairMapper.delete(id);
    }

    @Override
    public int remove(Serializable id) {
      return keyValuePairMapper.remove(id);
    }

    @Override
    public QueryResult<KeyValuePair> findPageInfo(BaseQuery baseQuery) {
        QueryResult<KeyValuePair> result = new QueryResult<KeyValuePair>();
        result.setQuery(baseQuery);
        Map
        <String, Object> params = result.getQuery().build();
        Integer amount = this.keyValuePairMapper.countPageInfo(params);
        result.setTotalRecord(amount);
        if (amount == 0) {
        return result;
        }
        List<KeyValuePair> list = keyValuePairMapper.findPageInfo(params);
        if (!CollectionUtils.isEmpty(list)) {
        result.setResultList(list);

        }
        return result;
    }
    public JSONObject change(JSONObject jsonObject, HashMap<String,String> map){
        for(String key:jsonObject.keySet()){
            String string = jsonObject.getString(key);
            String simpleName = jsonObject.get(key).getClass().getSimpleName();
            if(simpleName.equals("String")){
                jsonObject.put(key,map.get(string)==null?string:map.get(string));
            }
            if(simpleName.equals("JSONArray")){
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                for(int i = 0;i<jsonArray.size();i++){
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    change(jsonObject1,map);
                }
            }
        }
        return jsonObject;
    }

    @Override
    public String translaterMsg(TranslaterData translaterData) {
        String content = "";
        MessageModel messageModel = new MessageModel();
        messageModel.setJson(translaterData.getOldData());
        messageModel.setContent(translaterData.getChangeData());
        HashMap<String,String> map = new HashMap<>();
        if(translaterData.getKeyValuePair()!=null){
            String[] split = translaterData.getKeyValuePair().split(",");
            List<String> strings = Arrays.asList(split);
            List<KeyValuePair> byIds = findByIds(strings);
            if(byIds!=null){
                for(KeyValuePair keyValuePair:byIds){
                    map.put(keyValuePair.getKeyData(),keyValuePair.getValueData());
                }
            }
        }
        try {
            content= messageModel.render();
            System.out.println("#######################################"+content);
            JSONObject jsonObject = JSON.parseObject(content);
            if(content!=null&&map!=null&&jsonObject!=null){
                change(jsonObject,map);
            }
            content = JSON.toJSONString(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
    @Override
    public void translaterMsgToTopic(String  translaterId,String data) {
        TranslaterData translaterData = translaterDataService.findById(translaterId);
        translaterData.setOldData(data);
        String content = "";
        MessageModel messageModel = new MessageModel();
        messageModel.setJson(translaterData.getOldData());
        messageModel.setContent(translaterData.getChangeData());
        HashMap<String,String> map = new HashMap<>();
        if(translaterData.getKeyValuePair()!=null){
            String[] split = translaterData.getKeyValuePair().split(",");
            List<String> strings = Arrays.asList(split);
            List<KeyValuePair> byIds = findByIds(strings);
            if(byIds!=null){
                for(KeyValuePair keyValuePair:byIds){
                    map.put(keyValuePair.getKeyData(),keyValuePair.getValueData());
                }
            }
        }
        try {
            content= messageModel.render();
            System.out.println("#######################################"+content);
            JSONObject jsonObject = JSON.parseObject(content);
            if(content!=null&&map!=null&&jsonObject!=null){
                change(jsonObject,map);
            }
            content = JSON.toJSONString(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String kafkaTopic = translaterData.getKafkaTopic();
        HashMap<String,Object> param = new HashMap<>();
        param.put("status","true");
        param.put("type","set");
        List<Kafka> kafkas = kafkaService.findByNamedParamList(param);
        if(StringHelper.isNotEmpty(kafkaTopic)){
            if(kafkas.size()==0){
                return;
            }
            ProducerKafka producerKafka = new ProducerKafka(kafkas.get(0).getKafkaUrl());
            producerKafka.produce(kafkaTopic,JSON.toJSONString(content));
            System.out.println("发送到"+kafkaTopic+"&&&&&&&&&&&&&&&&&&"+JSON.toJSONString(content));
        }
    }
}
